package com.cnpc.framework.base.controller;

import com.alibaba.fastjson.JSON;
import com.cnpc.framework.annotation.RefreshCSRFToken;
import com.cnpc.framework.base.entity.BaseResponse;
import com.cnpc.framework.base.entity.User;
import com.cnpc.framework.base.entity.UserAvatar;
import com.cnpc.framework.base.pojo.PageInfo;
import com.cnpc.framework.base.pojo.Result;
import com.cnpc.framework.base.service.UserService;
import com.cnpc.framework.utils.DateUtil;
import com.cnpc.framework.utils.DownloadUtils;
import com.cnpc.framework.utils.ExcelExportUtil;
import com.lc.entity.UserTagChange;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 用户编辑
     *
     * @return
     */
    @RefreshCSRFToken
    @RequestMapping(method = RequestMethod.GET, value = "/edit")
    private String edit(String id, HttpServletRequest request) {

        request.setAttribute("id", id);
        return "base/user/user_edit";
    }

    /**
     * 用户列表
     */

    @RequestMapping(method = RequestMethod.GET, value = "/list")
    private String list() {
        return "base/user/user_list";
    }

    //用户列表 测试数据权限
    @RequestMapping(method = RequestMethod.GET, value = "/list_ff")
    private String listForFf() {
        return "base/user/user_ff_list";
    }


    @RequestMapping(method = RequestMethod.POST, value = "/save")
    @ResponseBody
    private Result saveUser(@RequestBody User user, HttpServletRequest request) {
        Result result = new Result(true);
        try {
            result = userService.editUser(user);
        } catch (Exception ex) {
            ex.printStackTrace();
            result = new Result(false,null,"系统繁忙！");

        }

        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/saveUserWithoutTags")
    @ResponseBody
    private Result saveUserWithoutTags(@RequestBody User user) {
        Result result = new Result(true);
        try {
            result = userService.editUserWithoutTags(user);
        } catch (Exception ex) {
            ex.printStackTrace();
            result = new Result(false,null,"系统繁忙！");

        }

        return result;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/editUserTags")
    @ResponseBody
    private Result editUserTags(@RequestBody UserTagChange userTagChange, HttpServletRequest request) {
        Result result = new Result(true);
        try {
            result = userService.editUserTags(userTagChange);
        } catch (Exception ex) {
            ex.printStackTrace();
            result = new Result(false,null,"系统繁忙！");

        }

        return result;
    }


    @RequestMapping(method = RequestMethod.POST, value = "/changeUserDept")
    @ResponseBody
    private Result changeUserDept(@RequestParam("userIds") List<String> userIds,@RequestParam("deptId") String deptId,String edituser) {
        Result result = new Result(true);
        try {
            result = userService.editUserDept(userIds,deptId,edituser);
        } catch (Exception ex) {
            ex.printStackTrace();
            result = new Result(false,null,"系统繁忙！");

        }

        return result;
    }


    @ResponseBody
    @RequestMapping(value = "verifyUser", method = RequestMethod.POST)
    public Result verifyUser(@RequestParam("id") String id,
                                      @RequestParam("state") int state,
                                      @RequestParam(value = "reason", required = false) String reason) {
        Result response;
        try {

            response = userService.updateUserState(id, state, reason);


        } catch (Exception ex) {
            ex.printStackTrace();
            response = new Result(false,null,"系统繁忙！");
        }
        return response;
    }

    @RequestMapping("/getUserList")
    @ResponseBody
    private Result getUserList(String name, String empNo, String sex,String arole,String deptId, String wrDeptId,String sh,String startTime,String endTime,Integer pageNum, Integer pageSize) {
        Result result = new Result();
        try {
            long cnt = userService.getUserCount(name, empNo, sex,arole,deptId, wrDeptId,sh,startTime,endTime);
            List<Map<String, Object>> list = null;
            if (cnt > 0) {
                list = userService.getUserList(name, empNo, sex,arole,deptId, wrDeptId,sh,startTime,endTime, pageNum, pageSize);
            }
            Map<String, Object> data = new HashMap<>();
            data.put("count", cnt);
            data.put("list", list);
            result.setSuccess(true);
            result.setData(data);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("系统内部错误！");
        }
        return result;
    }

    @RequestMapping("/getUserListByAuth")
    @ResponseBody
    private Result getUserListByAuth( @RequestParam("userId") String userId,String name, String empNo, String sex,String arole,String deptId, String sh,String startTime,String endTime,Integer pageNum, Integer pageSize) {
        Result result = new Result();
        try {
            if (StringUtils.isEmpty(userId)) {
                result.setSuccess(false);
                result.setMessage("参数缺失！");
                return result;
            }
            long cnt = userService.getUserCountByAuth(userId,name, empNo, sex,arole,deptId,sh,startTime,endTime);
            List<Map<String, Object>> list = null;
            if (cnt > 0) {
                list = userService.getUserListByAuth(userId,name, empNo, sex,arole,deptId,sh,startTime,endTime, pageNum, pageSize);
            }
            Map<String, Object> data = new HashMap<>();
            data.put("count", cnt);
            data.put("list", list);
            result.setSuccess(true);
            result.setData(data);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("系统内部错误！");
        }
        return result;
    }

    @RequestMapping("exportUserExcel")
    public void exportUserExcel(String name, String empNo, String sex,String arole,String deptId,String wrDeptId,String sh,String startTime,String endTime,
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            HttpServletResponse response) {
        try {

            List<Map<String, Object>> dataList = userService.getUserList(name, empNo, sex,arole,deptId, wrDeptId,sh,startTime,endTime,pageNum, pageSize);
            if (dataList == null || dataList.size() == 0) {
                return;
            }


            String[] title = {"员工编号","姓名", "手机", "身份证号", "部门", "入职时间", "性别", "生日", "民族", "登录名"};
            //excel文件名
            String fileName = "员工数据" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xls";
            //sheet名
            String sheetName = "员工数据";

            String content[][] = new String[dataList.size()][title.length];

            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> map = dataList.get(i);
                content[i][0] = map.get("empno") == null ? "" : map.get("empno").toString();
                content[i][1] = map.get("name") == null ? "" : map.get("name").toString();
                content[i][2] = map.get("mobile") == null ? "" : map.get("mobile").toString();
                content[i][3] = map.get("idcard") == null ? "" : map.get("idcard").toString();
                content[i][4] = map.get("deptName") == null ? "" : map.get("deptName").toString();
                content[i][5] = map.get("join_time") == null ? "" : map.get("join_time").toString();
                content[i][6] = map.get("sex") == null ? "" : map.get("sex").toString();
                content[i][7] = map.get("birthday") == null ? "" : map.get("birthday").toString();
                content[i][8] = map.get("nation") == null ? "" : map.get("nation").toString();
                content[i][9] = map.get("login_name") == null ? "" : map.get("login_name").toString();

            }

            HSSFWorkbook wb = ExcelExportUtil.getHSSFWorkbook(sheetName, title, content, null);
            DownloadUtils.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();


        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @RequestMapping(method = RequestMethod.POST, value = "/delete/{id}")
    @ResponseBody
    private Result deleteUser(@PathVariable("id") String id,String edituser) {
        Result result = new Result();

        try {
            result = userService.deleteUser(id,edituser);

        }
        catch (Exception e) {
            e.printStackTrace();
            return new Result(false,null,"用户数据被引用，不可删除！");
        }
        return new Result(true);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/deleteUsers")
    @ResponseBody
    private Result deleteUsers(@RequestParam("userIds") List<String> userIds, String edituser) {
        Result result = null;

        try {
            result = userService.deleteUsers(userIds,edituser);

        }
        catch (Exception e) {
            e.printStackTrace();
            return new Result(false,null,"用户数据被引用，不可删除！");
        }
        return result;
    }



    @RequestMapping(method = RequestMethod.POST, value = "/get")
    @ResponseBody
    private User getUser(String id) {
        return userService.getUserById(id);

    }

    /**
     * loadData
     *
     * @param pInfo
     * @param conditions
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/loadData")
    @ResponseBody
    public Map<String, Object> loadData(String pInfo, String conditions) {

        Map<String, Object> map = new HashMap<String, Object>();
        PageInfo pageInfo = JSON.parseObject(pInfo, PageInfo.class);
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
        pageInfo.setCount(userService.getCountByCriteria(criteria));
        map.put("pageInfo", pageInfo);
        map.put("data", userService.getListByCriteria(criteria, pageInfo));
        return map;
    }

    /**
     * tab方式curd demo
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/tab/list")
    private String tablist() {

        return "base/user/user_tab_list";
    }


    /**
     * 新的页面打开 curd demo
     */
    @RequestMapping(method = RequestMethod.GET, value = "/page/list")
    private String pagelist(String id, HttpServletRequest request) {
        request.setAttribute("selectId", id);
        return "base/user/user_page_list";
    }

    /**
     * 用户编辑 new page
     *
     * @return
     */
    @RefreshCSRFToken
    @RequestMapping(method = RequestMethod.GET, value = "/page/edit")
    private String pageEdit(String id, HttpServletRequest request) {

        request.setAttribute("id", id);
        return "base/user/user_page_edit";
    }

    /**
     * 用户头像上传 avatar
     */
    @RequestMapping(method = RequestMethod.GET, value = "/avatar")
    private String avatar(String userId, HttpServletRequest request) {
        request.setAttribute("userId", userId);
        return "base/user/user_avatar";
    }


    @RequestMapping(method = RequestMethod.POST, value = "/getAvatar")
    @ResponseBody
    private UserAvatar getAvatar(String userId) {
        return userService.getAvatarByUserId(userId);
    }

    @RequestMapping(value = "/select/{multiple}/{ids}/{callback}", method = RequestMethod.GET)
    public String selectUserPage(@PathVariable("multiple") String multiple,
                                 @PathVariable("ids") String ids,
                                 @PathVariable("callback") String callback, HttpServletRequest request) {
        request.setAttribute("multiple", multiple);
        request.setAttribute("ids", ids);
        request.setAttribute("callback", callback);
        return "base/user/user_select_list";
    }

    @RequestMapping(value = "/names", method = RequestMethod.POST)
    @ResponseBody
    public Map getNamesByIds(String ids) {
        Map<String, String> map = new HashMap<>();
        String names = userService.getUserNamesByUserIds(ids);
        map.put("name", names);
        return map;

    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/getOrgIdsAndBellow")
    public BaseResponse getOrgIdsAndBellow(String userId) {
        BaseResponse result =  new BaseResponse();

        try {

            List<String> orgIdsAndBellow = userService.getOrgIdsAndBellow(userId);
            result.setData(orgIdsAndBellow);

        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(1);
            result.setMessage("系统内部错误！");
        }
        return result;
    }

    @RequestMapping("importUserList")
    @ResponseBody
    public BaseResponse importUserList(@RequestParam("excel") MultipartFile excel) {
        BaseResponse response;
        try {
            response = userService.importUserList(excel);
        } catch (Exception ex) {
            ex.printStackTrace();
            response = new BaseResponse();
            response.setStatus(1);
            response.setMessage("系统繁忙");
        }
        return response;
    }

    @RequestMapping("getHigherOrgIds")
    @ResponseBody
    public BaseResponse getHigherOrgIds(@RequestParam("empId") String empId) {
        BaseResponse response = new BaseResponse();
        try {
            Map<String, Object> higherOrgIds = userService.getHigherOrgIds(empId);
            response.setData(higherOrgIds);
        } catch (Exception ex) {
            ex.printStackTrace();

            response.setStatus(1);
            response.setMessage("系统繁忙");
        }
        return response;
    }
}
